import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter_plugin_record_plus/const/play_state.dart';
import 'package:flutter_plugin_record_plus/const/response.dart';
import 'package:flutter_plugin_record_plus/flutter_plugin_record.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/xindong_permission_ctr.dart';
import 'package:xindong/utils/xindong_calender_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';

enum XinDongRecordVoiceState {
  none, // 未初始化/无权限
  allowRecording, // 允许录制（显示：开始录制/长按录制按钮）
  recording, // 录制中（显示：停止录制/松开停止按钮）
  completed, // 录制完成/播放结束（显示：重录/播放按钮）
  playing, // 播放中（显示：暂停播放按钮）
  playingPause, // 播放暂停中（显示：恢复播放按钮）
}

typedef XinDongRecordVoiceResultCallback = void Function(bool result, double seconds, String path);

class XinDongRecordVoiceCtr extends GetxController {
  static XinDongRecordVoiceCtr get to => Get.find();

  // 录音组件
  FlutterPluginRecord recordPlugin = FlutterPluginRecord();

  // 录制结果回调
  XinDongRecordVoiceResultCallback? _onRecordResult;

  // 是否有录音权限
  bool hasPermission = false;

  // 是否播放中
  bool isPlaying = false;

  // 是否暂停中
  bool isPause = false;

  // 是否录制录制中
  bool isRecording = false;

  // 是否录制完成
  bool recordCompleted = false;

  // 录音显示时长
  String timeText = "00:00";

  // 定时
  DateTime? _startTime;
  Timer? _countTimer;

  // 状态
  XinDongRecordVoiceState get voiceState {
    if (hasPermission) {
      // 录制中
      if (recordCompleted == false) {
        if (isRecording == false) {
          // 准备录制
          return XinDongRecordVoiceState.allowRecording;
        } else {
          // 在录制中
          return XinDongRecordVoiceState.recording;
        }
      } else {
        if (isPlaying == false && isPause == false) {
          return XinDongRecordVoiceState.completed;
        }
        if (isPause) {
          return XinDongRecordVoiceState.playingPause;
        }
        if (isPlaying) {
          return XinDongRecordVoiceState.playing;
        }
      }
    }
    return XinDongRecordVoiceState.none;
  }

  @override
  Future<void> onInit() async {
    super.onInit();
    // 初始化 推荐wav initRecordMp3()
    recordPlugin.init();

    // 初始化方法的监听
    recordPlugin.responseFromInit.listen((bool result) {
      mDebugPrint("初始化 ${result ? "成功" : "失败"}");
    });
    // 开始录制或结束录制的监听
    recordPlugin.response.listen((RecordResponse data) {
      if (data.msg == "onStart") {
        _createTimer();
        mDebugPrint("录音开始  ${data.success} ${data.msg} ${data.audioTimeLength} ${data.key}");
      } else if (data.msg == "onStop") {
        mDebugPrint("录音结束  ${data.success} ${data.msg} ${data.audioTimeLength} ${data.key}");
        _stopTimer();
        // 成功
        if (data.success == true && data.audioTimeLength != null && !TextUtil.isEmpty(data.path)) {
          final seconds = data.audioTimeLength ?? 0.0;
          if (seconds < 0) {
            showToast("说话时间太短");
            return _recordingFailed();
          } else {
            return _recordingSuccessful(data.audioTimeLength!, data.path!);
          }
        } else {
          return _recordingFailed();
        }
      }
    });

    // 录制过程监听录制的声音的大小 方便做语音动画显示图片的样式
    recordPlugin.responseFromAmplitude.listen((RecordResponse data) {
      var voiceData = double.parse(data.msg ?? '0');
      var tempVoice = "";
      if (voiceData > 0 && voiceData < 0.1) {
        tempVoice = "images/voice_volume_2.png";
      } else if (voiceData > 0.2 && voiceData < 0.3) {
        tempVoice = "images/voice_volume_3.png";
      } else if (voiceData > 0.3 && voiceData < 0.4) {
        tempVoice = "images/voice_volume_4.png";
      } else if (voiceData > 0.4 && voiceData < 0.5) {
        tempVoice = "images/voice_volume_5.png";
      } else if (voiceData > 0.5 && voiceData < 0.6) {
        tempVoice = "images/voice_volume_6.png";
      } else if (voiceData > 0.6 && voiceData < 0.7) {
        tempVoice = "images/voice_volume_7.png";
      } else if (voiceData > 0.7 && voiceData < 1) {
        tempVoice = "images/voice_volume_7.png";
      }
      // setState(() {
      //   voiceIco = tempVoice;
      //   if (overlayEntry != null) {
      //     overlayEntry.markNeedsBuild();
      //   }
      // });
      update();
      mDebugPrint("振幅大小：$voiceData  $tempVoice");
    });
    // 播放回调
    recordPlugin.responsePlayStateController.listen((PlayState playState) {
      mDebugPrint("播放状态：${playState.playState}"); // complete播放结束 false暂停 true恢复播放
      if (playState.playState == "complete") {
        isPlaying = false;
        isPause = false;
        update();
      }
    });
  }

  @override
  void onClose() {
    _countTimer?.cancel();
    _countTimer = null;
    recordPlugin.stop();
    recordPlugin.dispose();
    super.onClose();
  }

  // 检测
  Future<bool> checkPermission() async {
    bool hasMicrophonePermission = await XinDongPermissionCtr.checkPermission(XinDongAppPermission.microphone);
    bool hasStoragePermission = await XinDongPermissionCtr.checkPermission(XinDongAppPermission.audio);
    if (!hasMicrophonePermission || !hasStoragePermission) {
      hasPermission = true;
    } else {
      hasPermission = true;
    }
    return hasPermission;
  }

  // 重置录制
  Future resetRecord() async {
    isRecording = false;
    isPlaying = false;
    isPause = false;
    recordCompleted = false;
    timeText = "00:00";
    update();
  }

  // 开始录制
  Future startRecord({required XinDongRecordVoiceResultCallback onRecordResult}) async {
    if (!hasPermission) {
      debugPrint("没有获取麦克风存储权限");
      return;
    }
    if (isRecording == true) {
      debugPrint("在录制中");
      return;
    }
    _onRecordResult = onRecordResult;
    isRecording = true;
    recordCompleted = false;
    timeText = "00:00";
    update();
    return await recordPlugin.start();
  }

  // 停止录制
  Future stopRecord() async {
    return await recordPlugin.stop();
  }

  // 开始播放语音
  Future playVoice() async {
    isPlaying = true;
    update();
    return await recordPlugin.play();
  }

  // 暂停播放语音
  Future pausePlayVoice() async {
    isPause = !isPause;
    update();
    return await recordPlugin.pausePlay();
  }

  // 创建定时器
  void _createTimer() {
    _startTime = DateTime.now();
    _countTimer?.cancel();
    _countTimer = null;
    _countTimer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      final seconds = DateTime.now().difference(_startTime!).inSeconds;
      timeText = XinDongCalendarUtil.timeTextHMS(seconds);
      update();
    });
  }

  // 停止定时器
  void _stopTimer() {
    _countTimer?.cancel();
    _countTimer = null;
  }

  // 录制成功
  void _recordingSuccessful(double seconds, String path) {
    isRecording = false;
    isPlaying = false;
    isPause = false;
    recordCompleted = true;
    timeText = XinDongCalendarUtil.timeTextHMS(seconds.ceil());
    update();
    if (_onRecordResult != null) {
      _onRecordResult!(true, seconds, path);
    }
  }

  // 录制失败
  void _recordingFailed() {
    isRecording = false;
    isPlaying = false;
    isPause = false;
    recordCompleted = false;
    update();
    if (_onRecordResult != null) {
      _onRecordResult!(false, 0.0, "");
    }
  }
}
